import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as Path;
import '../../../../../lib_baseview/lib_baseview.dart';
import '../../../../../lib_baseview/utils/screen_utils.dart';
import '../../../../../lib_baseview/widget/dialogs.dart';
import '../../../../../lib_baseview/widget/textfield/jr_edit_text.dart';
import '../../../../../lib_baseview/widget/textfield/jr_text_field.dart';
import '../../../../../lib_baseview/widget/themes.dart';
import '../../../../../resource/language/generated/l10n.dart';
import '../model/room_music_mine_controller.dart';

class MusicUploadConfirmPage extends StatefulWidget {
  const MusicUploadConfirmPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MusicUploadConfirmPageState();
  }
}

class _MusicUploadConfirmPageState extends State<MusicUploadConfirmPage> {
  String sizeStr = '';
  int _currentIndex = 0;

  String get iconPath => _getFileIconAsset();
  String songName = '';
  String albumArt = '';
  int trackDuration = 0;
  TextEditingController? _songNameEditingController;
  TextEditingController? _singerNameEditingController;
  final mineController = Get.find<RoomMusicMineController>();

  List<UploadMusic> get musicNeedUpload => mineController.musicNeedUpload;

  UploadMusic? get musicCurrent => musicNeedUpload.length > _currentIndex
      ? musicNeedUpload[_currentIndex]
      : null;

  @override
  void initState() {
    super.initState();
    _songNameEditingController = TextEditingController();
    _singerNameEditingController = TextEditingController();
    load();
  }

  @override
  void dispose() {
    mineController.musicNeedUpload.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<RoomMusicMineController>(builder: (controller) {
      return Scaffold(
        appBar: AppBar(
          title: Text('upload_song_few'),
        ),
        resizeToAvoidBottomInset: false,
        body: _buildBody(),
      );

      // return CommonPage(
      //   title: T.current!
      //       .upload_song_few(_currentIndex + 1, musicNeedUpload.length),
      //   resizeToAvoidBottomInset: false,
      //   body: _buildBody(),
      // );
    });
  }

  _buildBody() {
    return GestureDetector(
      onTap: () {
        ///收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        color: Colors.white,
        padding: EdgeInsetsDirectional.only(
            bottom: ScreenUtils.ins.iphoneXBottom, start: 20, end: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(
              height: 16,
            ),
            _buildTitleRow(),
            const SizedBox(height: 6),
            _buildStepTitle(T.current!.upload_song, '(.mp3, .m4a)'),
            const SizedBox(height: 18),
            _buildFileInfo(),
            const SizedBox(height: 24),
            _getDesText(T.current!.song_name),
            const SizedBox(height: 12),
            _buildNameInputText(
                _songNameEditingController, T.current!.please_input_song_name),
            const SizedBox(height: 20),
            _getDesText(T.current!.singer_name),
            const SizedBox(height: 12),
            _buildNameInputText(_singerNameEditingController,
                T.current!.please_input_singer_name),
            const Spacer(),
            JRButton(title: T.current!.confirm, onPressed: _onConfirmTapped),
            const SizedBox(height: 30),
          ],
        ),
      ),
    );
  }

  Widget _buildTitleRow() {
    return Container(
      alignment: AlignmentDirectional.centerStart,
      child: Row(
        children: [
          Expanded(
            child: Text(
              songName,
              style: const TextStyle(
                  color: RColors.textBlack,
                  fontSize: 24,
                  fontWeight: FontWeight.w600),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          InkWell(
            onTap: () async {
              if (_currentIndex < musicNeedUpload.length - 1) {
                _currentIndex += 1;
                await load();
              } else {
                Navigator.of(context).pop(true);
              }
            },
            child: Container(
              padding: const EdgeInsetsDirectional.only(start: 15),
              child: Text(T.current!.remove,
                  style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: RColors.buttonYellow)),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildStepTitle(String title, String attachTitle) {
    return Row(
      children: [
        Text(
          title,
          style: const TextStyle(
            color: RColors.textBlack,
            fontSize: 14,
            fontWeight: FontWeight.w600,
          ),
        ),
        const SizedBox(width: 4),
        Text(
          attachTitle,
          style: const TextStyle(
            color: RColors.textGuide,
            fontSize: 14,
            fontWeight: FontWeight.w400,
          ),
        )
      ],
    );
  }

  Future<String> _getHumanReadSize() async {
    int bytes = await getFileSize(musicCurrent?.path ?? '');
    // return GlobalUtil.formatBytes(bytes, decimals: 1);
    return 'ddddd';
  }

  Future<int> getFileSize(String filePath) async {
    if (filePath.isEmpty) {
      return 0;
    }
    File file = File(filePath);
    bool s = await file.exists();
    if (s == true) {
      FileStat stat = await file.stat();
      return stat.size;
    }
    return 0;
  }

  Widget _buildNameInputText(TextEditingController? controller, String hint) {
    return JRTextField(hintText: hint, controller: controller);
  }

  String _getFileIconAsset() {
    String filePath = musicCurrent?.path ?? '';
    if (filePath.isEmpty) {
      return '';
    }
    if (filePath.endsWith('.mp3')) {
      return 'ic_mp3.webp';
    }
    if (filePath.endsWith('.m4a')) {
      return 'ktv_ic_m4a.webp';
    }
    if (filePath.endsWith('.lrc')) {
      return 'ktv_ic_lrc.webp';
    }
    return '';
  }

  Widget _getDesText(String text) {
    return Text(
      text,
      style: const TextStyle(
          color: Color(0xff666666), fontSize: 14, fontWeight: FontWeight.w400),
    );
  }

  load() async {
    sizeStr = await _getHumanReadSize();

    // /// 读存 歌曲名 歌手名 和 封面
    // var metadata =
    //     await MetadataRetriever.fromFile(File(musicCurrent?.path ?? ''));
    // var trackName = musicCurrent?.name ?? (metadata.trackName ?? '');
    // var artistName = '';
    // List<String> artistList = metadata.trackArtistNames ?? [];
    // if (artistList.isNotEmpty) {
    //   artistName = artistList.first;
    // }
    // albumArt = '';
    // if (metadata.albumArt != null) {
    //   File file = File(Path.join(
    //       GlobalConfig.instance.appDirectory.path, 'upload/temp.jpg'));
    //   if (await file.exists()) {
    //     file.deleteSync(recursive: true);
    //   }
    //   file.writeAsBytesSync(metadata!.albumArt as List<int>);
    //   albumArt = file.path;
    // }

    // RLog.d('$trackName , $artistName');
    // _songNameEditingController?.text = trackName;
    // _singerNameEditingController?.text = artistName;
    // songName = trackName;
    // trackDuration = (metadata?.trackDuration ?? 0) ~/ 1000;
    // if (songName.isEmpty) {
    //   songName = T.current!.some_song(_currentIndex + 1);
    // }

    // if (mounted) setState(() {});
  }

  Widget _buildFileInfo() {
    return Row(
      children: [
        if (iconPath.isNotEmpty) image(iconPath, width: 40, height: 40),
        const SizedBox(width: 5),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                Path.basename(musicCurrent?.path ?? ''),
                style: const TextStyle(color: RColors.textBlack, fontSize: 14),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 6),
              Text(
                sizeStr,
                style: const TextStyle(
                    color: RColors.textGuide,
                    fontSize: 11,
                    fontWeight: FontWeight.w400),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ],
    );
  }

  _onConfirmTapped() async {
    if (_songNameEditingController?.text.trim().isEmpty ?? true) {
      showToast(T.current!.song_name_cant_empty);
      return;
    }
    if (_singerNameEditingController?.text.trim().isEmpty ?? true) {
      showToast(T.current!.singer_name_cant_empty);
      return;
    }

    ///歌曲ID
    // int songCode = NumUtil.parseInt(Path.basenameWithoutExtension(musicCurrent));
    int songCode = musicCurrent?.songCode ?? 0;

    ///歌曲封面
    String albumArtTos = '';

    /// 演唱者
    String singer = _singerNameEditingController?.text ?? '';

    ///歌曲名称
    String songName = _songNameEditingController?.text ?? '';

    ///歌曲下载地址
    String songUrl = '';

    showLoadingDialog(status: T.current!.uploading);

    ///如果有封面上传封面到tos
    // if (albumArt.isNotEmpty) {
    //   albumArtTos =
    //       await TosUploadUtils.uploadImageByTos(localFilePath: albumArt) ?? '';
    // }

    ///上传音频
    // songUrl = await TosUploadUtils.uploadByTos(
    //         localFilePath: musicCurrent?.path ?? '', sceneCode: 104) ??
    //     '';
    // dismissLoadingDialog();
    // if (songUrl.isEmpty) {
    //   showToast(T.current!.upload_song_fail);
    // } else {
    //   Music music = Music(
    //       songCode: songCode,
    //       durationS: trackDuration,
    //       poster: albumArtTos,
    //       singer: singer,
    //       name: songName,
    //       releaseTime: songUrl);
    //   BaseRspResult result =
    //       await RtcApi.instance.addMineMusic(jsonEncode(music.toJson()));
    //   if (result.isSuccess) {
    //     showToast(T.current!.upload_song_suc);
    //     mineController.addMusic(music);
    //     if (_currentIndex == musicNeedUpload.length - 1) {
    //       Get.back();
    //     } else {
    //       _currentIndex += 1;
    //       await load();
    //       if (mounted) setState(() {});
    //     }
    //   } else {
    //     showToast(result.errorMsg ?? T.current!.request_fail);
    //   }
    // }
  }
}
